package com.xunqi.product.service.impl;

import com.xunqi.product.entity.AttrEntity;
import com.xunqi.product.service.AttrService;
import com.xunqi.product.vo.AttrGroupWithAttrsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunqi.common.utils.PageUtils;
import com.xunqi.common.utils.Query;

import com.xunqi.product.dao.AttrGroupDao;
import com.xunqi.product.entity.AttrGroupEntity;
import com.xunqi.product.service.AttrGroupService;
import org.w3c.dom.Attr;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params,Long catelogId) {
        IPage<AttrGroupEntity> page = null;
        String key = params.get("key").toString();
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();

        if (!key.isEmpty()){
            wrapper.and((obj)->{
                obj.eq("attr_group_id",key).or().like("attr_group_name",key);
            });
        }

        if (catelogId!=0){
            wrapper.eq("catelog_id",catelogId);
        }
        page = this.page(new Query<AttrGroupEntity>().getPage(params),wrapper);

        return new PageUtils(page);
    }

    /**
     * 根据分类id查出所有的分组以及组里的属性
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrsVo> getWithAttrsByCatelogId(Long catelogId) {

        List<AttrGroupEntity> entities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        List<AttrGroupWithAttrsVo> collect = entities.stream().map(item -> {
            AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(item, vo);
            List<AttrEntity> attr = attrService.getRelation(vo.getAttrGroupId());
            vo.setAttrs(attr);
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

}